package com.itheima.nio.buffer.demo06;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 服务端代码
 */
public class NioServerDemo01 {

    public static void main(String[] args) throws IOException {

        // 1. 打开一个ServerSocketChannel通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 2. 绑定端口号
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));

        // 3. 设置为非阻塞模式
        serverSocketChannel.configureBlocking(false) ;

        while(true) {

            // 4. 获取连接
            SocketChannel socketChannel = serverSocketChannel.accept();

            // 判断socketChannel是否为null
            if(socketChannel != null) {

                // 5. 创建Buffer对象(用于从通道中读取数据)
                ByteBuffer allocate = ByteBuffer.allocate(1024);

                // 6. 读取数据到Buffer中
                int read = socketChannel.read(allocate);
                while(read > 0) {
                    allocate.flip();                                    // 做读写转换
                    byte[] array = allocate.array();                    // 把ByteBuffer转换成字节数组
                    System.out.print(new String(array , 0 , read));
                    allocate.clear() ;                                  // 清空
                    read = socketChannel.read(allocate);
                }

                System.out.println("接收到了客户端所发送过来的数据....................");

                // 给客户端进行响应
                ByteBuffer byteBuffer = ByteBuffer.wrap("OK,收到了".getBytes("UTF-8"));
                socketChannel.write(byteBuffer) ;

                // 7. 释放资源
                socketChannel.close();

            }

        }

    }

}
